package network;

import java.awt.GridLayout;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Server extends JFrame{

	private int port = 2600;
	private Object object = null;
	private volatile NetworkPackage[] nps = new NetworkPackage[4];
	private List<JLabel> labels = new ArrayList<JLabel>();
	private List<Thread> threads = new ArrayList<Thread>();
	
	public Server(){
		for(int i = 0; i<4; i++){
			labels.add(new JLabel("Default", JLabel.CENTER));
			threads.add(new Thread(new Runnable() {
				@Override
				public void run() {
					try {		
						int port = getPort();
						System.out.println("Listening for connection...");
						Socket socket = Network.listenForConnection(port);
						System.out.println("Port "+port+" is connected");
						while(true){
							try{
								long start = System.currentTimeMillis();
								Object object = Network.readObject(socket);	
								long end = System.currentTimeMillis();
								System.out.println(end-start);
								Network.sendObject(nps, socket);								
								NetworkPackage np = (NetworkPackage)object;
								nps[np.getId()] =  np;
								labels.get(np.getId()).setText("X = "+np.getX()+", Y = "+np.getY());
							}
							catch (SocketException e) {	}
						}			
					}  catch (IOException e) {
						e.printStackTrace();
					}		
				}
			}));
		}
		for(Thread thread : threads){
			thread.start();
		}
		setLayout(new GridLayout(4,1));
		for(JLabel label : labels){
			add(label);
		}
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(200,200);
		setVisible(true);
		
	}
	
	public static void main(String[] arg){
		new Server();
	}
	
	public synchronized int getPort(){
		port++;
		return port-1;
	}
	
}
